package com.example.designhbwxz.book.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod;

/**
 * Http 工具类
 *
 * @author shenzw
 * @date 2023/10/24
 */
public class HttpClientUtils {

    public static JSONObject execute(String url, HttpMethod httpMethod) {
        HttpRequestBase http = null;

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // 根据 HttpMethod 进行 HttpRequest 的创建
            if (HttpMethod.GET == httpMethod) {
                http = new HttpGet(url);
            } else {
                http = new HttpPost(url);
            }

            HttpEntity entity = client.execute(http).getEntity();
            return JSON.parseObject(EntityUtils.toString(entity));
        } catch (Exception e) {
            return JSON.parseObject("Request failed！url = " + url);
        }

    }
}
